(function(obj) {
	obj.baseUrl;
	obj.userid;
	obj.xAuthToken;
	obj.beforeSend=function(request) {
        request.setRequestHeader("xAuthToken",obj.xAuthToken);
    };
    obj.onerror=function(data){
    	console.log(data);
    };
    
    var _s3;
	var _s3Config = {
			accessKeyId: '', 
			secretAccessKey: '',
			sessionToken: '', 
			region:'cn-north-1',
			bucket:''
	};
    function _initS3(){
		$.ajax({
			  type: 'POST',
			  url: obj.baseUrl+'/u/getS3Token',
			  traditional: true,
			  async: false,
			  beforeSend:obj.beforeSend,
			  success: function(data){
				  if(data.code == 1){
					  	var awsInfo = data.obj;
				        for (var key in awsInfo) {
				            if (typeof awsInfo[key] !== 'undefined') {
				            	_s3Config[key] = awsInfo[key];
				            }
				        }
				        AWS.config.update(_s3Config);
		    			_s3 = new AWS.S3({
		    			  apiVersion: '2006-03-01'
		    			});
		    			console.log("_initS3 成功");
				  }else{
					  obj.onerror(data);
				  }
			  }
		});
    };
    obj.upload = (paramData) => {
		 return new Promise((resovle, reject) => {
			 	var file = paramData.file;
			 	var path = paramData.path;
			 	
				var key = path+file.name;
				var ContentType = file.type;
				 var params = {
						  Bucket: _s3Config.bucket, 
						  Body:file,
						  Key: key,
						  ContentType:ContentType
						 };
				 _s3.upload(params, function(err, data) {
					 if(err){
						 reject(err);			 
					 }else{
						 resovle(data);
					 }
				 });
			 });
	};
	
	obj.wsConnect = () => {
		//var host = "ws://"+baseUrl+'/socket';
		var host = "ws://"+window.location.host+baseUrl+"/socket?xAuthToken="+obj.xAuthToken;
		console.log(host);
		window.WebSocket = window.WebSocket || window.MozWebSocket;
		if(!window.WebSocket) { // 检测浏览器支持  
			this.onerror('Error: WebSocket is not supported .');
			return;
		}
		var socket = new WebSocket(host); // 创建连接并注册响应函数  
		socket.onopen = function() {
			console.log("ws open");
		};
		socket.onmessage = function(message) {
			var data = eval('(' + message.data + ')');
			console.log(message);
			_receiveMessage(data.message.id);//处理回执消息
			if(data.type == 1){//聊天消息
				obj.chatMessageHandler(data.message);
			}else if(data.type == 2){//系统消息
				obj.sysMessageHandler(data.message);
			}
		};
		socket.onclose = function() {
			console.log("ws close");
		};
		socket.onerror = function(errorMsg) {
			console.log("ws error:"+errorMsg);
		};
	};
	obj.chatMessageHandler = (message) => {
		
	};
	obj.sysMessageHandler = (message) => {
		
	};
	function _receiveMessage(msgid){
		$.ajax({
			  type: 'POST',
			  beforeSend:obj.beforeSend,
			  url: baseUrl+'/im/receiptMessage',
			  traditional: true,
			  data: {
				  msgid:msgid
			  },
			  success: function(data){
				  //console.log(data);
			  },
			  error: function (data) {
				  console.error("_receiveMessage error"+data);
		      }
		});
	}
    obj.retryFun = (retriesCount, fn) => {
    	return new Promise((resovle, reject) => {
    		var attempt = () => {
        		fn().then(resovle).catch(err => {
            		if(retriesCount > 0){
            			setTimeout(attempt, 3000);
            			retriesCount--;
            		}else{
            			reject(err);
            		}
            	});
        	};
        	attempt();
    	});
    }; 
    obj.createGroup = (paramData) => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        async: true,
			        traditional:true,
			        beforeSend:obj.beforeSend,
			        data: {
			        	ids: paramData.ids
			        },
			        url: baseUrl+'/im/createGroup',
			        success: function (data,status,xhr) {
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	};
    obj.inGroup = (paramData) => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        async: true,
			        traditional:true,
			        beforeSend:obj.beforeSend,
			        data: {
			        	groupid:paramData.groupid,
			        	ids: paramData.ids
			        },
			        url: baseUrl+'/im/inGroup',
			        success: function (data,status,xhr) {
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	};
	obj.removerGroup = (paramData) => {
		return new Promise((resovle, reject) => {
			$.ajax({
				type: "POST",
				async: true,
				traditional:true,
				beforeSend:obj.beforeSend,
				data: {
					groupid:paramData.groupid,
					ids: paramData.ids
				},
				url: baseUrl+'/im/removerGroup',
				success: function (data,status,xhr) {
					resovle(data);
				},
				error: function (data) {
					reject(data);
				}
			});
		});
	};
	obj.outGroup = (paramData) => {
		return new Promise((resovle, reject) => {
			$.ajax({
				type: "POST",
				async: true,
				traditional:true,
				beforeSend:obj.beforeSend,
				data: {
					groupid:paramData.groupid
				},
				url: baseUrl+'/im/outGroup',
				success: function (data,status,xhr) {
					resovle(data);
				},
				error: function (data) {
					reject(data);
				}
			});
		});
	};
	obj.getGroupMen = (paramData) => {
		return new Promise((resovle, reject) => {
			$.ajax({
				type: "POST",
				async: true,
				traditional:true,
				beforeSend:obj.beforeSend,
				data: {
					groupid:paramData.groupid
				},
				url: baseUrl+'/im/getGroupMembers',
				success: function (data) {
					resovle(data);
				},
				error: function (data) {
					reject(data);
				}
			});
		});
	};
	obj.login = (paramData) => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        async: true,
			        data: {
			        	password: paramData.password,
			        	phone: paramData.phone,
			        	source: paramData.source
			        },
			        url: baseUrl+'/u/login',
			        success: function (data,status,xhr) {
			        	if(data.code == 1){
			        		  console.log("登录成功");
							  var xAuthToken = xhr.getResponseHeader("xAuthToken");
							  obj.xAuthToken = xAuthToken;
							  obj.userid = data.obj.userid;
							  _initS3();
						}
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	};
	obj.getContacts = () => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        beforeSend:obj.beforeSend,
			        async: true,
			        url: baseUrl+'/im/getContacts',
			        success: function (data,status,xhr) {
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	};
    obj.sendMsg = (paramData) => {
    	var _sendMsg = () => {
        	return new Promise((resovle, reject) => {
        		$.ajax({
    		        type: "POST",
    		        async: true,
    		        beforeSend:obj.beforeSend,
    		        data: {
    		        	to:paramData.to,
    		        	content:paramData.content,
    		        	clientid:paramData.clientid,
    		        	type:paramData.type,
    		        	ctype:paramData.chatType,
    		        },
    		        url: baseUrl+'/im/sendMessage',
    		        success: function (data,status,xhr) {
    		        	resovle(data);
    		        },
    		        error: function (data) {
    		        	reject(data);
    		        }
    		    });
    		});
    	};
    	var p =obj.retryFun(5,_sendMsg);
    	return p;
	};  
	obj.getSession = () => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        beforeSend:obj.beforeSend,
			        async: true,
			        url: baseUrl+'/im/getSession',
			        success: function (data,status,xhr) {
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	};
	obj.revokeMessage = (paramData) => {
		 return new Promise((resovle, reject) => {
				$.ajax({
			        type: "POST",
			        beforeSend:obj.beforeSend,
			        async: true,
			        data: {
			        	msgid:paramData.msgid
    		        },
			        url: baseUrl+'/im/revokeMessage',
			        success: function (data,status,xhr) {
			        	resovle(data);
			        },
			        error: function (data) {
			        	reject(data);
			        }
			    });
		});
	}; 
	obj.sendaddGoodFriend = (paramData) => {
		return new Promise((phone, isReply) => {
			$.ajax({
				type: "POST",
				beforeSend:obj.beforeSend,
				async: true,
				data: {
					phone:paramData.phone,
					isReply:paramData.isReply
				},
				url: baseUrl+'/im/sendaddGoodFriend',
				success: function (data) {
					alert(JSON.stringify(data));
					console.log(data);
					if(data.code==31){
						alert("不能重复添加好友");
					}else if(data.code==32){
						alert("添加好友不存在");
					}else if(data.code==1){
						alert(true);
					}else{
						alert("未知异常");
					}
					resovle(data);
				},
				error: function (data) {
					reject(data);
				}
			});
		});
	}; 
})(IM = {});